#include "pthread.h"
#include "unistd.h"
#include "stdint.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

uint8_t sqr(uint8_t num)
{
    uint8_t value = num * num;
    sleep(1);
    return value;
}

void *sum_sqr(void *num)
{
    uint8_t *value = (uint8_t *)malloc(sizeof(uint8_t));
    *value = sqr(*(uint8_t *)num);
    return value;
}

int main(int argc, char const *argv[])
{
    printf("主线程启动\n");
    long start, end;
    struct timeval tv;
    gettimeofday(&tv, NULL);
    start = tv.tv_sec;
    uint8_t num_arr[5] = {1, 2, 3, 4, 5};
    uint8_t ptr[5] = {0};
    printf("start time: %ld\n", start);

    pthread_t thread[5];
    for (uint8_t i = 0; i < 5; i++)
    {
        pthread_create(&thread[i], NULL, sum_sqr, &num_arr[i]);
    }
    for (uint8_t i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(thread[i], &result);
        ptr[i] = *(uint8_t *)result;
    }
    gettimeofday(&tv, NULL);
    end = tv.tv_sec;
    uint8_t sum = 0;
    for (uint8_t i = 0; i < 5; i++)
    {
        sum += ptr[i];
    }
    printf("sum: %d\n", sum);
    printf("end time: %ld\n", end);
    printf("time: %ld\n", end - start);
    printf("主线程结束\n");
}
